#!/bin/bash
# chkconfig: 2345 90 10
# description: A secure socks5 proxy, designed to protect your Internet traffic.

### BEGIN INIT INFO
# Provides:          ShadowsocksR
# Required-Start:    $network $syslog
# Required-Stop:     $network
# Default-Start:     2 3 4 5
# Default-Stop:      0 1 6
# Short-Description: Fast tunnel proxy that helps you bypass firewalls
# Description:       Start or stop the ShadowsocksR server
### END INIT INFO

# Intro:  https://github.com/onekeyshell/kcptun_for_ss_ssr/issues

NAME=ShadowsocksR
BIN=/usr/local/shadowsocksR/shadowsocks/server.py
CONF=/usr/local/shadowsocksR/shadowsocksR.json
version="2.0"
RETVAL=0
[ -x ${BIN} ] || exit 0
if [ ! -r ${CONF} ]; then
    echo "config file ${CONF} not found"
    exit 1
fi
check_running(){
    PID=`ps -ef | grep -v grep | grep -i "${BIN}" | awk '{print $2}'`
    if [ ! -z $PID ]; then
        return 0
    else
        return 1
    fi
}

do_start(){
    check_running
    if [ $? -eq 0 ]; then
        echo "$NAME (pid $PID) is already running..."
        exit 0
    else
        $BIN -c $CONF -d start
        RETVAL=$?
        if [ $RETVAL -eq 0 ]; then
            echo "Starting $NAME success"
        else
            echo "Starting $NAME failed"
        fi
    fi
}

do_stop(){
    check_running
    if [ $? -eq 0 ]; then
        $BIN -c $CONF -d stop
        RETVAL=$?
        if [ $RETVAL -eq 0 ]; then
            echo "Stopping $NAME success"
        else
            echo "Stopping $NAME failed"
        fi
    else
        echo "$NAME is stopped"
        RETVAL=1
    fi
}

do_status(){
    check_running
    if [ $? -eq 0 ]; then
        echo "$NAME (pid $PID) is running..."
    else
        echo "$NAME is stopped"
        RETVAL=1
    fi
}

do_restart(){
    do_stop
    do_start
}

do_config(){
    vi ${CONF}
}

do_version(){
    ${BIN} --version
}

case "$1" in
    start|stop|restart|status|config)
    do_$1
    ;;
    [vV][eE][rR][sS][iI][oO][nN]|-[vV][eE][rR][sS][iI][oO][nN]|--[vV][eE][rR][sS][iI][oO][nN]|-[vV]|--[vV])
        do_version
    ;;
    *)
    echo "Usage: $0 { start | stop | restart | status | config | version }"
    RETVAL=1
    ;;
esac

exit $RETVAL
